package middleware

import (
	"Sailor/app/Sailor-console-server/internal/consts"
	"Sailor/app/Sailor-console-server/utility/utility_casbin"
	"Sailor/app/Sailor-console-server/utility/utility_jwt"
	"github.com/gogf/gf/v2/net/ghttp"
	"net/http"
)

func AuthorityHandler(r *ghttp.Request) {
	var Authorization string
	Authorization = r.Request.Header.Get(consts.AuthorizationText)
	if Authorization == "" {
		cookie, err := r.Request.Cookie(consts.AuthorizationText)
		if err != nil {
			r.Response.WriteStatusExit(http.StatusUnauthorized)
			return
		}
		Authorization = cookie.Value
	}

	userInfo, err := utility_jwt.ParseToken(r.Context(), Authorization)
	if err != nil {
		r.Response.WriteStatusExit(http.StatusUnauthorized)
		return
	}
	//获取请求的PATH
	obj := r.Request.URL.Path
	// 获取请求方法
	act := r.Request.Method
	// 获取用户的角色
	sub := userInfo.UserRole
	e := utility_casbin.CasBin(r.Context()) // 判断策略中是否存在
	success, _ := e.Enforce(sub, obj, act)
	if !success {
		r.Response.WriteStatusExit(http.StatusForbidden)
		return
	}
	r.SetCtxVar(consts.CtxUserInfoKey, userInfo)
	r.Middleware.Next()
}
